2019年7月13日

複習

  • 建立 R 的使用環境
  • 熟悉 R 語言基礎操作
    • 敘述句、數列
    • 查詢說明檔
  • 了解 R 語言的物件的結構
    • 變數型態:logical、numeric、character、factor
    • 資料存放容器:list、data.frame、matrix、c()
    • 特別的物件:NA、NaN、Inf

複習

  • 常用技巧
    • 看部分資料及擷取
    • 更改、新增、刪除欄列
    • 文字處理
  • R 語言的流程控制
    • if、else
    • for loop
    • 自訂 function

資料分析流程

  • 資料採集
  • 資料清洗處理
  • 視覺呈現
  • 統計及分析
  • 報告產出

資料分析 in R

What is Markdown?

  • 啟發自2004年純文字電子郵件
  • 好寫、好讀
  • 可以純文字發布
  • Markdown
    • Light weight markup language
    • Remove HTML tag for higher readibility.
    • Inline HTML is avaliable.
    • HTML5 Introduction (w3schools.com)

What is RMarkdown?

  • 可以在 Markdown 內嵌 R code
  • 一次呈現執行程式碼後的結果及文字說明
  • 不用再把圖、表複製到其他文件編輯器中
  • Rmd -> md -> html (docx, pdf)

Why we need R Markdown?

  • 時間久了會忘記code的意思
  • 要寫說明文件給同學、同事、教授、主管
  • 教授很有想法,想嘗試新方法
    (WTF!又要重跑一份)
  • 老闆說要改流程
    (想扁人!之前貼到簡報上的圖又要重貼一份)
  • 專案報告要呈現,code改了,但是文件無法同時修改!

Why we need R Markdown?

  • 製作reproducible的報告、投影片
  • 想寫數學式子好展現自己的專業 \(e=mc^2\)
  • 只有一份source code,不需要額外複製圖片到報告中
  • 需求更改時,可以動態改變報告內容
  • 增加資料分析演算法的可讀性

前置作業 - 安裝

  • 最新版的RStudio已經包含R Markdown功能
  • 你也可以透過以下指令安裝R Markdown套件:
install.packages("rmarkdown")

R Markdown 快速導覽

打開你第一個RMarkdown

Document

Overview

Markdown

R Code Chunks

Inline R Code and Equations

  • 利用 `r` 在markdown中插入R程式
  • 插入 LaTeX 公式的方法:
    • 行內$ equation $
    • 段落 $$ equation $$
  • for example :

Markdown Basics

Markdown Quick Reference

在RStudio中,也可以找到RMarkdown的作弊小文件!

標題!

Headers

  • 字體大小:使用井字號
  • 井字越多,字體越小
    • # Header 1
    • ## Header 2
    • ### Header 3
    • #### Header 4
    • ##### Header 5
    • ###### Header 6

字體!

  • 我是正常文字
  • 粗體:使用**bold**__bold__
  • 斜體:使用 *italics*_italics_
  • 刪除線:使用~~想扁人~~

結果:

  • 我是正常文字
  • 粗體:bold
  • 斜體:italics
  • 刪除線:想扁人

Attach pictures

  • 貼上照片
  • img: inserting images into an HTML document.

    Much easier for adjusting width and height.

    <img  src="img/me.jpg" width="80"> #src=路徑,jpg、png皆可
    <img  src="img/me.jpg" height="100" width="500">

先來簡單的複製貼上!

  • 利用+*-,列點文字
  • 嵌入圖片: image: ![](path/to/smallorb.png)
  • 嵌入連結:[木下柚香](https://youtu.be/RlmeFHIwzKA?t=88)
  • 嵌入表格:
       標題一    |   標題二     
    -------------|------------- 
        123      |    456        
        789      |    0.0        
標題一 標題二
123 456
789 0.0

Exercise - 1

請大家以下面的文字為樣板,打出一篇簡短的自我介紹:

大家好,我是Jax(1.使用粗體),目前就讀於國立政治大學,興趣是:

(2.請列點)

  • 跳舞
  • 打球
  • 玩桌遊

我是男生,我長這樣: (3.請放照片)

(4.請放你的臉書連結) 想要和我做朋友的人可以加我臉書 歡迎加我好友

Answer - 1

大家好,我是**Jax**(1.使用粗體),目前就讀於國立政治大學,興趣是:\

- 跳舞\
- 打球\
- 玩桌遊\


我是男生,我長這樣:![](你的圖片路徑) 

想要和我做朋有的人可以加我[臉書](臉書路徑)

R Code Chunks

Overview

  • 在 R Code Chunk 中,code可以被執行
  • code會被```{r}及 ```包圍
  • 快捷鍵(for windows、mac):alt + control + i / option + command + i
  • 將下列文字複製貼上並Knit:

```{r}
summary(cars$dist)
```
summary(cars$dist)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
   2.00   26.00   36.00   42.98   56.00  120.00 

命名 R code chunks


```{r plot}
summary(cars)
plot(cars)
```

Basic Chunk Options - 1

  • R Markdown 預設為同時顯示程式碼與所有回傳到 console 上的訊息 (output)
  • echo(T/F): 是否顯示程式碼,output一定會呈現
  • eval(T/F): 是否要執行程式碼
  • message(T/F): 程式碼附帶訊息是否要含在output
  • include(T/F): 程式碼及output是否要呈現,程式碼仍會執行
  • warning(T/F): 是否呈現warning訊息

小問題

  • 如果今天output跟程式碼都不要顯示,該如何打?
  • include = F

  • 如果今天只想顯示output,該如何打?
  • echo = F

  • 如果今天只想呈現程式碼,不想執行程式,該如何打?
  • eval = F

  • 如果今天output跟程式碼都要呈現,該如何打?
  • include = T 或照預設

Basic Chunk Options - 2

常用

  • defult:show code and output
  • echo = FALSE :only show output
  • eval = FALSE :only show code
  • include = FALSE : run code but don't show code & output

Basic Chunk Options - 3

利用每個chunk右上的設定鍵

執行部分chunk

在編輯 RMarkdown 的過程中,想要測試 chunk 中的 code 是否成功,但又不想要每次檢查都 knit,不僅花費太多不必要的時間也浪費系統資源

  • 將游標點選在想要測試的 chunk 中任何一個位置
  • chunks 選單中,點選 Run Current Chunk
  • 快捷鍵:Alt + Ctrl + C

Exercise - 2.1

請大家利用 iris 的資料依照不同的品種,

畫出 Sepal.Length 及 Petal.Length 的 scatter plot

可先用R script畫出

Answer - 2.1

plot(x=iris$Sepal.Length,y=iris$Petal.Length, 
     pch=ifelse(iris$Species == 'setosa', 7, 
                ifelse(iris$Species == 'versicolor', 8, 13)),
     col = ifelse(iris$Species == 'setosa', 'red', 
          ifelse(iris$Species == 'versicolor', 'blue', 'green')),main = "Demo" ,
     xlab = "Sepal.Length",ylab="Petal.Length") 

Exercise - 2.2

請大家在 Rmarkdown 中產出將剛剛的 scatter plot

Answer - 2.2

第一個chunk


```{r, echo=TRUE, message=TRUE, warning=TRUE}
library(dplyr)
library(ggplot2)
```

如果不要出現額外訊息,怎麼調整?

第二個chunk


```{r}
iris %>% 
  ggplot(aes(x=Sepal.Length, y=Petal.Length, color=Species)) + 
  geom_point(shape=1, size=2) 
```

Exercise - 2.3

原始網頁

Rmarkdown 呈現

Exercise - 3.1

利用R Markdown 製作《一周天氣預報》書面報告。

  • 計算12/03日當日的最高溫與最低溫度

Hint:

  1. 下載weather.csv到自己的電腦上
  2. 在R chunk中,利用read.csv()讀取檔案進行分析
  3. 找出12/03當日最高溫 max()
  4. 找出12/03當日最低溫 min()
  5. use inline R code `r max()`

Answer - 3.1

利用R Markdown 製作《一周天氣預報》書面報告。

  • 計算七天中最高溫與最低溫及平均溫差(小數點第2位)
dat <- read.csv("C:/Users/DELL/Desktop/NCCU/工作坊/data/weatherWin.csv") 
max(dat[,5])
min(dat[,4])
round(mean(dat[,5])-mean(dat[,4]),2)
# 預測高溫約`r max(dat[1:2,4:5])`度,低溫約`r min(dat[1:2,4:5])`度
# 平均溫差為`r round(mean(dat[,5])-mean(dat[,4]),2)`度

預測高溫約30度,低溫約20度,平均溫差為3.86度

Table in Rmarkdown

呈現表格 in Rmarkdown - 1

  • Print data directly:
print(head(women))
  height weight
1     58    115
2     59    117
3     60    120
4     61    123
5     62    126
6     63    129

呈現表格 in Rmarkdown - 1

  • 不用手動 key in 表格
  • 在 Chunk 後面的參數多加上results='asis'
  • 在 Chunk 裡面打上knitr::kable,呈現表格在output上
```{r, results='asis'}
knitr::kable(women)
```

呈現表格 in Rmarkdown - 1

height weight
58 115
59 117
60 120
61 123
62 126
63 129

呈現表格 in Rmarkdown - 2

  • DT 套件
  • 未安裝者記得先安裝 install.packages("DT")
  • 使用前記得 library(DT)
  • 易於呈現、美化表格
  • DT使用手冊
ex:

```{r}
datatable(head(iris))
```

呈現表格 in Rmarkdown - 2

  • 調整表格呈現的列數
  • 使用 options = list(pageLength = 數字) 參數調整
# 呈現三列
datatable(iris, options = list(pageLength = 3))
# 呈現五列
datatable(cars, options = list(pageLength = 5)) 

呈現表格 in Rmarkdown - 2

  • 可以利用 html 語法修改字體
  • 標記特殊欄或列
  • 調整欄
datatable(iris) %>%
  formatStyle('Sepal.Length',  color = 'red', 
              backgroundColor = 'orange', fontWeight = 'bold')

呈現表格 in Rmarkdown - 2

  • 調整列
datatable(cars) %>% formatStyle( 'dist' ,
  target = 'row',
  backgroundColor = styleEqual(c(10), c('pink'))
)

呈現表格 in Rmarkdown - 2

Table of Contents

目錄

  • Rmarkdown 有提供目錄的功能如R課前講義
  • 文件長時方便尋找

新增目錄

  • 將以下複製貼上到Rmarkdown的開頭
  • theme: united 表示目錄的主題選擇為 united,可以變動
  • R Markdown Theme Gallery
---
title: "你Rmarkdown的名稱"
author: "名字"
date: "2019/07/13"
output:
  html_document:
    theme: united
    toc : true
    toc_float: true
---

新增目錄

  • 報告內圖片的長寬可以變動:透過fig_width以及fig_height: 7.5參數調整
  • toc_depth表示顯示到多大的標題
    • ex: toc_depth: 4 會顯示有少於或等於四個井字號 #### 的標題
---
title: "你Rmarkdown的名稱"
author: "名字"
date: "2019/07/13"
output:
  html_document:
    theme: united
    fig_width: 10
    fig_height: 7.5
    toc : true
    toc_depth: 4
    toc_float: true
---

Rmarkdown 內建主題選擇

  • 可以透過點選的方式選則整個 RMD 的主題
  • 其餘改變的項目
  • 設定小圖示 -> Output Options

除了輸出 HTML

Persentation - 1

  • Rmarkdown 除了可以輸出 HTML 文件外,可以生成投影片

Persentation - 2

  • ## 代表一張投影片
  • # 主題黑幕
  • 要注意因為每張投影片長度限制,所以須控制內容

Flexdashboard - 1

Flexdashboard - 2

參考作品

小組報告練習

請各位同學分成5-8組,每組各做出一個R markdown報告。
報告內容為 :
每個人的

  • 小組自我介紹
  • 一張照片
  • 一個連結 (如Exercise - 1)

最後利用早上的demo資料(也可用R內鍵資料iris、cars等),用dplyr套件,挖掘資料,主題不限,看小組對甚麼有興趣。 最好可以用圖表達出來,如plot、hist、barplot…等

Appendix

Interactive Documents

It’s possible to embed a Shiny application within a document.

  • hack_yaml hack_yaml

Publish to the web

Using R packages::slidify to publish your slides to the web

library(slidify)
publish_github("repo", username="user_name")
publish_rpubs("title","file_name.html")
publish_dropbox(dir_name)
publish_gist("title",file="file_name.html",publish=TRUE)

Publish to the web: Github

  1. sign up or login in Github.com at browser
  2. find button: New repository to add new one.
  3. select a name for repository, then created.
  4. the link of your new repository would be like:
    https://github.com/"your_name"/"repo_name".git
  5. find Settings in your profile at top-right corner
  6. select SSH Keys and add SSH Key
  7. upload your SSH key which created by your own PC/notebook.
  8. at RStudio, using Rcommand:
    slidify::publish_github("repo_name", username="your_name")
  9. your new page will be ready in 5~10 min and link:
    https://"your_name".github.io/"repo_name"/index.html

Source

Wush 教學影片

繼續學習之路

Thank You!